package model.humanbody

import groovy.transform.CompileStatic
import model.agent.Agent
import model.agent.AgentInterface
import model.agent.AgentVariable
import model.agent.AgentVariableInterface

import org.apache.poi.hssf.usermodel.*

/**
 * 人体类,实现了model.humanbody.BodyInterface接口，是模型的入口。
 */
@CompileStatic
public class HumanBody extends Agent implements BodyInterface{
	
	def int ticks = 0
	
	def HumanBody(){
		this.name = "人体"
	}

	//脚本用setter
	def propertyMissing(String name, int value) {setCondition(name,value)}

	//脚本用getter
	def propertyMissing(String name) { getCondition(name) }

	@Override
	public void addOrgan(AgentInterface organ) {
		this.addSubAgent(organ)
	}

	/**
	 * 找到指定的variable，返回其所在agent。找不到则返回null
	 * @param name variable的名字
	 * @return variable的所在agent，找不到则返回null
	 */
	public AgentInterface searchVariableOnAgent(String name){
		AgentInterface p = null
		if(variables.containsKey(name)){
			p = this
		}else{
			subAgents.each{String key, AgentInterface agent ->
				def o = (Organ)agent
				if(o.variables.containsKey(name)){
					p = agent
					return p
				}
			}
		}
		//if (p == null ) throw new Exception("\"${name}\"不存在")
		return p
	}

	/**
	 * 找到指定的variable，返回variable。找不到则返回null
	 * @param name variable的名字
	 * @return variable本身，找不到则返回null
	 */
	public AgentVariableInterface searchVariable(String name){
		AgentInterface agent = searchVariableOnAgent(name)

		if(agent){
			return (AgentVariable)agent.getVariable(name)
		}
		//println "here"
		return null
	}

	/**
	 * variable的setter
	 */
	@Override
	public void setCondition(String var, int value) {
		AgentInterface p = searchVariableOnAgent(var)
		if(p==null){throw new NoSuchElementException("\"${var}\"不存在")}
		p.setVarValue(var, value)
		
	}

	/**
	 * variable的getter
	 */
	@Override
	public int getCondition(String var) {
		AgentInterface p = searchVariableOnAgent(var)

		//println (p.getPValue(variable))
		if(p==null){throw new NoSuchElementException("\"${var}\"不存在")}
		return p.getVarValue(var)
	}


	/**
	 * 模型所有变量归零，重新从relations文件夹下读取脚本
	 */
	@Override
	public void reset() {
		this.resetVars()
		subAgents.each{String key, AgentInterface agent ->
			agent.resetVars()
		}

	}

	/**
	 * 返回所有variable的值，数据接口是个树状的HashMap
	 */
	@Override
	public HashMap getStatus() {
		def status = this.getVarsMap()
		subAgents.each {String key, AgentInterface agent ->
			status[key] = agent.getVarsMap()
		}

		return status
	}


}

